package com.cloud.school.bus.teacherhelper.modules.login;

import org.apache.http.Header;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.text.method.DigitsKeyListener;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.cloud.school.bus.teacherhelper.base.utils.AppUserId;
import com.cloud.school.bus.teacherhelper.base.utils.SaveUserOperate;
import com.cloud.school.bus.teacherhelper.entitys.LoginSetting;
import com.cloud.school.bus.teacherhelper.modules.SlidingActivity;
import com.cloud.school.bus.teacherhelper.modules.login.baseactivity.BaseLoginActivity;
import com.cloud.school.bus.teacherhelper.protocol.baseresponse.BaseJsonHttpResponse;
import com.cloud.school.bus.teacherhelper.protocol.classstudent.GetClassinfoRequest;
import com.cloud.school.bus.teacherhelper.protocol.classstudent.GetClassinfoResponse;
import com.cloud.school.bus.teacherhelper.protocol.login.GetTsigninRequest;
import com.cloud.school.bus.teacherhelper.protocol.login.GetTsigninResponse;
import com.cloud.school.bus.teacherhelper.protocol.login.LoginSettingRequest;
import com.cloud.school.bus.teacherhelper.protocol.login.LoginSettingResponse;
import com.cloud.school.bus.teacherhelper.R;
import com.umeng.analytics.MobclickAgent;
import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.onClick.OnClickNetworkStatusListener;

/**
 * 登陆界面
 * 
 * @author lenovo
 * 
 */
public class LoginActivity extends BaseLoginActivity {

	private DigitsKeyListener mDigitsKeyListener = DigitsKeyListener
			.getInstance("0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		init();
	}

	@Override
	protected void init() {
		super.init();
		// guokr001
		mUserNameEditTextClearView.getEditText().setText(
				AppUserId.getUserName(mContext));
//		mUserNameEditTextClearView.getEditText().setKeyListener(
//				mDigitsKeyListener);
		mPasswordEditTextClearView.getEditText().setText(
				AppUserId.getPassword(mContext));
//		mPasswordEditTextClearView.getEditText().setKeyListener(
//				mDigitsKeyListener);
		mUserNameEditTextClearView.getEditText().setSingleLine();
		mUserNameEditTextClearView.getEditText().setFocusable(true);
		mUserNameEditTextClearView.getEditText().requestFocus();
		mUserNameEditTextClearView.getEditText().setFocusableInTouchMode(true);
		mUserNameEditTextClearView.getEditText().setSingleLine();
		mUserNameEditTextClearView.getEditText().setImeOptions(
				EditorInfo.IME_ACTION_NEXT);

		mPasswordEditTextClearView.getEditText().setImeOptions(
				EditorInfo.IME_ACTION_DONE);
		mPasswordEditTextClearView.getEditText().setSingleLine();
		mPasswordEditTextClearView.getEditText().setTransformationMethod(new PasswordTransformationMethod());
		mPasswordEditTextClearView.getEditText().setOnKeyListener(
				new OnKeyListener() {

					@Override
					public boolean onKey(View view, int keyCode, KeyEvent event) {
						if (KeyEvent.KEYCODE_ENTER == keyCode
								&& event.getAction() == KeyEvent.ACTION_DOWN) {
							StringBuilder errorStringBuilder = new StringBuilder();
							if (!checkStartUse(errorStringBuilder)) {
								// error
								HandlerToastUI.getHandlerToastUI(mContext,
										errorStringBuilder.toString());
							} else {
								memberCheckLogin();
							}
							return true;
						}
						return false;
					}
				});

		setListener();
	}

	@Override
	protected void setListener() {

		Button loginButton = (Button) findViewById(R.id.loginButton);
		loginButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				StringBuilder errorStringBuilder = new StringBuilder();
				if (!checkStartUse(errorStringBuilder)) {
					// error
					HandlerToastUI.getHandlerToastUI(mContext,
							errorStringBuilder.toString());
				} else {
					memberCheckLogin();
				}
			}
		});

		super.setListener();
	}

	/**
	 * 会员登陆,手机号登陆
	 */
	private void memberCheckLogin() {
		// "guokr001", "111111"
		NetworkClient.getNetworkClient().PostRequest(
				new GetTsigninRequest(mContext, mUserNameEditTextClearView
						.getEditText().getText().toString(),
						mPasswordEditTextClearView.getEditText().getText()
								.toString()), new GetTsigninResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
						String errorString = getString(R.string.enter_corrent_account_and_password);
						if ("1".equals(code)) {
							// 成功
							AppUserId.setUserName(mContext,
									mUserNameEditTextClearView.getEditText()
											.getText().toString());
							AppUserId.setPassword(mContext,
									mPasswordEditTextClearView.getEditText()
											.getText().toString());
							LoginSetting();
						} else if ("-1010".equals(code)) {
							// 用户名或密码错误
							HandlerToastUI.getHandlerToastUI(mContext,
									errorString);
						} else if ("-3".equals(code)) {
							// 用户名或密码不能为空
							HandlerToastUI.getHandlerToastUI(mContext,
									errorString);
						} else if ("-4".equals(code)) {
							// 密码不能包含特殊字符
							HandlerToastUI.getHandlerToastUI(mContext,
									errorString);
						} else {
							HandlerToastUI.getHandlerToastUI(mContext,
									errorString);
						}
					}
				});
	}

	private void LoginSetting() {
		NetworkClient.getNetworkClient().GetRequest(
				new LoginSettingRequest(mContext), new LoginSettingResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
						mApplication.mLoginSetting = loginSetting;
						DebugLog.logI(loginSetting.toString());

						getClassinfo(new Runnable() {

							@Override
							public void run() {
								jumpActivity();
							}
						});

					}
				});
	}

	public void getClassinfo(final Runnable runnable) {
		if (null == mApplication.mClassInfo || null == mApplication.mTeacher
				|| null == mApplication.mStudentList) {
			NetworkClient.getNetworkClient().GetRequest(
					new GetClassinfoRequest(this), new GetClassinfoResponse() {
						@Override
						public void onResponse(
								ResponseHandlerInterface responseHandlerInterface) {

							if ("1".equals(code)) {
								mApplication.mClassInfo = classInfo;
								mApplication.mTeacher = teacher;
								mApplication.mStudentList = studentList;
								HandlerPostUI.getHandlerPostUI(runnable);
							} else if ("-4".equals(code)) {
								// HandlerToastUI.getHandlerToastUI(
								// SlidingActivity.this, "不存在班级");
							}
						}
					});
		} else {
			HandlerPostUI.getHandlerPostUI(runnable);
		}
	}

	/**
	 * 跳转界面
	 * 
	 * @param flag
	 *            0:手机号获取验证码地跳转，1:联合登陆跳转
	 */
	private void jumpActivity() {
		Intent intent = new Intent(mContext, SlidingActivity.class);
		startActivity(intent);
		finish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void quit() {
		System.exit(0);
		finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			quit();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
}
